const koa = require('koa');
const app = new koa();
const render = require('koa-art-template');
const router = require('koa-router')();
const path = require('path')
const DB = require('./modules/db');
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
render(app, {
    root: path.join(__dirname, 'views'),
    extname: '.html', //后缀也可以写成.art
    debug: process.env.NODE_ENV !== 'production'
});
router.get('/', async ctx => {
    var idValue= "<p>hello world</p>"
    var data = await DB.find("user", {});
    await ctx.render('index', {
        data,
        idValue
    })
})
router.get('/detail', async ctx => {
    await ctx.render("detail", {
        detail: "详情"
    })
})
router.get('/add',async ctx=>{
    await ctx.render('add')
})
router.post('/doAdd',async ctx=>{
  var data = await DB.insert("user", ctx.request.body);
  try{
      if(data.result.ok){
          ctx.redirect('/')
      }
  }catch(err){
      console.log(err)
      ctx.redirect('/add')
  }
})
router.get('/edit',async ctx=>{
    // 获取用户传递的id
    let id = ctx.query.id;
    // 从数据库中查询数据
    let data  =await DB.find("user",{_id:DB.getObjectId(id)});
    await ctx.render('edit',{
        list:data[0]
    });
})
router.post('/doEdit',async ctx=>{
    var {name,age,id} = ctx.request.body;
    let data = await DB.update("user",{"_id":DB.getObjectId(id)},{name,age});
    try{
        if(data.result.ok){
            ctx.redirect('/')
        }
    }catch(err){
        console.log(err)
        ctx.redirect('/edit')
    }
})
router.get('/delete',async ctx=>{
     let id = ctx.query.id;
     let data = await DB.remove("user",{"_id":DB.getObjectId(id)});
     try{
        if(data.result.ok){
            ctx.redirect('/')
        }
    }catch(err){
        console.log(err)
        ctx.redirect('/')
    }
})
app.use(router.routes()).use(router.allowedMethods())
app.listen(8080)